package com.zust513.controller;

import com.zust513.dto.UserDTO;
import com.zust513.service.UserService;
import com.zust513.service.OrderService;
import com.zust513.service.CourierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员身份管理控制器
 */
@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private CourierService courierService;

    /**
     * 管理员身份管理页面 (F00404) - 使用简化版页面
     */
    @GetMapping("/admin-management")
    public String adminManagementPage(Model model) {
        List<UserDTO> admins = userService.getAllAdmins();
        model.addAttribute("admins", admins);
        model.addAttribute("view", "admin/admin-management-simple");  // 使用简化版模板文件
        return "admin/index";
    }

    /**
     * 显示添加管理员表单
     */
    @GetMapping("/add-admin-form")
    public String showAddAdminForm(Model model) {
        model.addAttribute("view", "admin/add-admin-form");
        return "admin/index";
    }

    /**
     * 处理添加管理员表单提交
     */
    @PostMapping("/add-admin")
    public String addAdminSubmit(
            @ModelAttribute UserDTO userDTO,
            RedirectAttributes redirectAttributes) {
        try {
            UserDTO savedAdmin = userService.addAdmin(userDTO);
            redirectAttributes.addFlashAttribute("successMessage", "管理员添加成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "添加管理员失败: " + e.getMessage());
        }
        return "redirect:/admin/admin-management";
    }

    /**
     * 删除管理员
     */
    @GetMapping("/delete-admin/{userId}")
    public String deleteAdmin(
            @PathVariable Integer userId,
            RedirectAttributes redirectAttributes) {
        try {
            // 确��只能删除管理员用户
            UserDTO existingAdmin = userService.getUserById(userId);
            if (existingAdmin == null || !"admin".equals(existingAdmin.getRole())) {
                redirectAttributes.addFlashAttribute("errorMessage", "只能删除管理员用户");
                return "redirect:/admin/admin-management";
            }

            boolean success = userService.deleteUser(userId);
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "管理员删除成功");
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "删除管理员失败");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "删除管理员失败: " + e.getMessage());
        }
        return "redirect:/admin/admin-management";
    }

    /**
     * 管理员控制台首页
     */
    @GetMapping({"", "/"})
    public String dashboardPage(Model model) {
        try {
            // 获取总订单数
            Integer totalOrders = orderService.getTotalOrdersCount();
            model.addAttribute("totalOrders", totalOrders != null ? totalOrders : 0);

            // 获取配送员数量
            Integer totalCouriers = courierService.getTotalCouriersCount();
            model.addAttribute("totalCouriers", totalCouriers != null ? totalCouriers : 0);

            // 获取最近的订单（最多显示5条）
            List<Map<String, Object>> recentOrders = orderService.getRecentOrders(5);
            model.addAttribute("recentOrders", recentOrders);

        } catch (Exception e) {
            // 如果查询失败，使用默认值
            model.addAttribute("totalOrders", 0);
            model.addAttribute("totalCouriers", 0);
            model.addAttribute("recentOrders", new ArrayList<>());

            // 记录错误日志
            System.err.println("控制台数据查询失败: " + e.getMessage());
            e.printStackTrace();
        }

        model.addAttribute("view", "admin/dashboard");
        return "admin/index";
    }

    /**
     * API接口：获取所有管理员列表
     */
    @GetMapping("/api/management/admins")
    @ResponseBody
    public ResponseEntity<List<UserDTO>> getAllAdmins() {
        List<UserDTO> admins = userService.getAllAdmins();
        return ResponseEntity.ok(admins);
    }

    /**
     * API接口：修改路径匹配前端请求
     */
    @GetMapping("/management/admins")
    @ResponseBody
    public ResponseEntity<List<UserDTO>> getAllAdminsAlt() {
        return getAllAdmins();
    }

    /**
     * API接口：获取指定管理员信息
     */
    @GetMapping("/api/management/admins/{userId}")
    @ResponseBody
    public ResponseEntity<UserDTO> getAdminById(@PathVariable Integer userId) {
        UserDTO admin = userService.getUserById(userId);
        if (admin == null || !"admin".equals(admin.getRole())) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(admin);
    }

    /**
     * API接口：获取指定管理员信息 - 修改路径匹配���端请求
     */
    @GetMapping("/management/admins/{userId}")
    @ResponseBody
    public ResponseEntity<UserDTO> getAdminByIdAlt(@PathVariable Integer userId) {
        return getAdminById(userId);
    }

    /**
     * API接口：添加管理员
     */
    @PostMapping("/api/management/admins")
    @ResponseBody
    public ResponseEntity<?> addAdmin(@RequestBody UserDTO userDTO) {
        try {
            UserDTO savedAdmin = userService.addAdmin(userDTO);
            return ResponseEntity.status(HttpStatus.CREATED).body(savedAdmin);
        } catch (IllegalArgumentException e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * API接口：添加管理员 - 修改路径匹配前端请求
     */
    @PostMapping("/management/admins")
    @ResponseBody
    public ResponseEntity<?> addAdminAlt(@RequestBody UserDTO userDTO) {
        return addAdmin(userDTO);
    }

    /**
     * API接口：更新管理员信息
     */
    @PutMapping("/api/management/admins/{userId}")
    @ResponseBody
    public ResponseEntity<?> updateAdmin(
            @PathVariable Integer userId,
            @RequestBody UserDTO userDTO) {

        // 确保ID一致
        userDTO.setUserId(userId);

        // 确保只能修改管理员用户
        UserDTO existingAdmin = userService.getUserById(userId);
        if (existingAdmin == null || !"admin".equals(existingAdmin.getRole())) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "只能修改管理员用户");
            return ResponseEntity.badRequest().body(error);
        }

        boolean success = userService.updateUser(userDTO);
        if (success) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * API接口：更新管理员信息 - 修改路径匹配前端请求
     */
    @PutMapping("/management/admins/{userId}")
    @ResponseBody
    public ResponseEntity<?> updateAdminAlt(
            @PathVariable Integer userId,
            @RequestBody UserDTO userDTO) {
        return updateAdmin(userId, userDTO);
    }

    /**
     * API接口：删除管理员
     */
    @DeleteMapping("/api/management/admins/{userId}")
    @ResponseBody
    public ResponseEntity<?> deleteAdmin(@PathVariable Integer userId) {
        // 确保只能删除���理员用户
        UserDTO existingAdmin = userService.getUserById(userId);
        if (existingAdmin == null || !"admin".equals(existingAdmin.getRole())) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "只能删除管理员用户");
            return ResponseEntity.badRequest().body(error);
        }

        boolean success = userService.deleteUser(userId);
        if (success) {
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * API接口：删除管理员 - 修改路径匹配前端请求
     */
    @DeleteMapping("/management/admins/{userId}")
    @ResponseBody
    public ResponseEntity<?> deleteAdminAlt(@PathVariable Integer userId) {
        return deleteAdmin(userId);
    }

    /**
     * 显示编辑管理���表单
     */
    @GetMapping("/edit-admin-form/{userId}")
    public String showEditAdminForm(@PathVariable Integer userId, Model model, RedirectAttributes redirectAttributes) {
        try {
            UserDTO admin = userService.getUserById(userId);
            if (admin == null || !"admin".equals(admin.getRole())) {
                redirectAttributes.addFlashAttribute("errorMessage", "找不到指定的管理员用户");
                return "redirect:/admin/admin-management";
            }
            model.addAttribute("admin", admin);
            model.addAttribute("view", "admin/edit-admin-form");
            return "admin/index";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "获取管理员信息失败: " + e.getMessage());
            return "redirect:/admin/admin-management";
        }
    }

    /**
     * 处理编辑管理员表单提交
     */
    @PostMapping("/edit-admin/{userId}")
    public String editAdminSubmit(
            @PathVariable Integer userId,
            @ModelAttribute UserDTO userDTO,
            RedirectAttributes redirectAttributes) {
        try {
            // 确保ID一致
            userDTO.setUserId(userId);

            // 确保只能修改管理员用户
            UserDTO existingAdmin = userService.getUserById(userId);
            if (existingAdmin == null || !"admin".equals(existingAdmin.getRole())) {
                redirectAttributes.addFlashAttribute("errorMessage", "只能修改管理员用户");
                return "redirect:/admin/admin-management";
            }

            // 如果密码为空，则不更新密码
            if (userDTO.getPassword() == null || userDTO.getPassword().isEmpty()) {
                userDTO.setPassword(null);
            }

            // 确保角色不变
            userDTO.setRole("admin");

            boolean success = userService.updateUser(userDTO);
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "管理员信息更新成功");
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "更新管理员信息失败");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "更新管理员信息失败: " + e.getMessage());
        }
        return "redirect:/admin/admin-management";
    }
}
